package com.example.util;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.response.AlipayTradeQueryResponse;

import org.springframework.stereotype.Component;

@Component
public class PayUtil {
    //个人appid，
    private final String APP_ID = "9021000150604912";
    //编码格式
    private final String CHARSET = "UTF-8";
    //秘钥生成工具生成的 应用私钥
    private final String APP_PRIVATE_KEY = "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCQiLMLA0DbmmImV/kj8OlBzZfvU0EXqc7D36XbeCJgkMU8jTsgcjlxWuBIG4bsLe5bicy3ErT30LMIDKGsfnYYXYJ2JwwJnY7v52wgM3Xkqthsn9mLQPzXloKsYR9PXR++cBCR/+/r1NJc6SbCbH5PjjpZW6wmSdEtri+v3ZOtfQllZHXs8Qx7ouaeMZyBIqel+pJPxXHgF9naexD68PLN/V/bS95CiXUKTwGW2fwbHhnxtNFm5s9VPezWgQ/uEhLps7zKpPLuvQ4CS44Vqh4BwEPQqCgMt2v9t6lbXIEQq82qs0wLvZaHrUMNgcyLojGISL7hzMEMHholWnlNC1FBAgMBAAECggEAR9can2uzjjQTexmZJYs2ddW6ImQQY7Gsq2F78DWraLIsx2cvr3X3JWfVOSItkzFVW7yHu6uZtd/PTT3yEmodSwkXsqC/8/uTs50k+nB5tfpRbtSZbgUUaBhQxVvVEz6na6IKKne7ik4TbckZ0ePZeLOqPwY48CMazQjafSC2qbFQfVF85XFXnh3cWH2rRKXqL/5g06u79x0vgdaVXsSH/hg+Rr3EoG19C1KyfqaUHty4RSaUOcy0i3TwAkAzJKxCmmAv4fBoW3ZF80GIDd6beeMw2S1y4fLQfkJ2apsMv6TvQRGBDSyxbFgOwcxdmejesO6N2WHpMDYZINflFzkbrQKBgQDDoOeZRRa7zbfkJ/7zNnaqkLSc19IsWxl1eFC3nj2SHnIj/DiHFLMm+/hEbE9aBn/TeHOH9ig7sxpmQ0I22JXf8VcDRcc9+AQ3msQcrJfGF8u/A1gYUYySOBjDmXLfRtUR/yk5N2TEAG+mf9Ugt8m77fOafuYlJ6bY85wBqqnR2wKBgQC9IzW6+TSAiyupBKFkvKuCsOmAa10r7LR3rTVRfB7zXXT9lzLf/buKwj6FAy0hjfGHve0hzDah920oq0aqFN52lQlhVaXuRWQx9IMOLKPmskEy8yiIAbnYf41V7OeF5mZuiz3bq9I6Y8UqvlvVI5W/0KCEeenJiw3dm7QwRImaEwKBgFoAQezSy0W1vD98Yx/z055fGqj55djARLM1mjUP2RXLagnCNSN4U3/A9pRMHCm3ycE5rjVD+3iTyrZ3hRQEitdPig+YX7TT0OTgEA99HApn0jXbzQDLK9ftdP8wLpgoV0iDUqzfHj3KUZORRjVaOLZ8H9HZRfqcBnfTg9eEc8J3AoGBAKG3EELMvuJFnFAIgIJkevTklNHTereKzQciltsUGFaXCuektsAj742F5fTOsXDmL6STdMSYGgJETxYd0+6qp0eWyI1rsNNYi4HXAZNGAeHHec25cGdRqnh9Hvhf9dlcFSrhbUN81uRL2BJi7pv/sBNwqz56CrXjajiX3+oBP/H3AoGAWOGqyT7uDriyPEm1pVrxfWMBjvx1LENADA8ZeAdus4fbU/qfu8+Rej9TNo4Be+GDSlin88hAQEVo9lVaP8NKYNY8zRNrwZUg23YAKUZkS//i29oPBD2cusrYSjbK4h3hNpWoT6ed9EaLSqCkQ2B74fhnbPoPT8zrc+qM5vPdhxE=";
    // 支付宝公钥，这是在沙箱应用-接口加签方式-自定义秘钥-  添加应用公钥以后生成的支付宝公钥
    private final String ALIPAY_PUBLIC_KEY = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAkIizCwNA25piJlf5I/DpQc2X71NBF6nOw9+l23giYJDFPI07IHI5cVrgSBuG7C3uW4nMtxK099CzCAyhrH52GF2CdicMCZ2O7+dsIDN15KrYbJ/Zi0D815aCrGEfT10fvnAQkf/v69TSXOkmwmx+T446WVusJknRLa4vr92TrX0JZWR17PEMe6LmnjGcgSKnpfqST8Vx4BfZ2nsQ+vDyzf1f20veQol1Ck8Bltn8Gx4Z8bTRZubPVT3s1oEP7hIS6bO8yqTy7r0OAkuOFaoeAcBD0KgoDLdr/bepW1yBEKvNqrNMC72Wh61DDYHMi6IxiEi+4czBDB4aJVp5TQtRQQIDAQAB";
    // 支付宝网关地址，沙箱应用页面可直接查看
    private final String GATEWAY_URL = "https://openapi-sandbox.dl.alipaydev.com/gateway.do";
    // 请求格式
    private final String FORMAT = "JSON";
    // 加密算法
    private final String SIGN_TYPE = "RSA2";
    //支付宝异步通知路径,付款完毕后会先异步调用本方法,必须为公网地址,优先在这里做业务逻辑处理
    //但是由于这里需要外网，我们在本地测试可以使用内网穿透的方式模拟公网ip请求
    private final String NOTIFY_URL = "http://c36775dc.natappfree.cc/api/alipay/notify";
    //支付宝同步通知路径,也就是当付款完毕后，可以自定义跳转本项目的自定义页面,可以不是公网地址,可以调到我的订单页面
    private final String RETURN_URL = "http://localhost:8080/api/alipay/return";

    private AlipayClient alipayClient = null;
    /**
     * 向支付宝发送支付请求
     *
     * @param outTradeNo  商户订单号
     * @param totalAmount 订单总金额
     * @param subject     订单标题
     */
    public String sendRequestToAlipay(String outTradeNo, Float totalAmount, String subject) throws AlipayApiException {
        // 初始化AlipayClient，配置支付宝网关、应用ID、私钥等参数
        alipayClient = new DefaultAlipayClient(GATEWAY_URL, APP_ID, APP_PRIVATE_KEY, FORMAT, CHARSET, ALIPAY_PUBLIC_KEY, SIGN_TYPE);
        // 创建支付宝支付请求对象
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        // 设置异步回调地址（支付宝服务器异步通知商户服务器的地址）
        alipayRequest.setNotifyUrl(NOTIFY_URL);
        // 设置同步回调地址（用户付款后跳转的页面）
        alipayRequest.setReturnUrl(RETURN_URL);
        //商品描述（可空）
        String body = "";
        // 构建业务参数JSON对象
        JSONObject bizContent = new JSONObject();
        bizContent.put("out_trade_no", outTradeNo);
        bizContent.put("total_amount", totalAmount);
        bizContent.put("subject", subject);
        bizContent.put("body", body);
        bizContent.put("product_code", "FAST_INSTANT_TRADE_PAY");
        alipayRequest.setBizContent(bizContent.toJSONString()); // 注意使用toJSONString()
        // 执行支付请求并获取返回结果
        String result = alipayClient.pageExecute(alipayRequest).getBody();
        System.out.println("返回的结果："+result );
        return result;
    }

    /**
     * 查询指定订单的信息
     *
     * @param id 订单编号
     * @return 支付查询结果的原始响应体
     */
    public String query(String id){
        AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();
        // 构建业务参数JSON对象
        JSONObject bizContent = new JSONObject();
        // 商户订单号
        bizContent.put("out_trade_no", id);
        request.setBizContent(bizContent.toString());
        AlipayTradeQueryResponse response = null;
        String body=null;
        try {
            // 执行查询请求并获取响应
            response = alipayClient.execute(request);
            body = response.getBody();
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        if(response.isSuccess()){
            System.out.println("调用成功");
        } else {
            System.out.println("调用失败");
        }
        return body;
    }
}
